//
//  Dic+Extension.swift
//  ReportScan
//
//  Created by woniu on 2025/8/20.
//

import Foundation

extension Dictionary {
    
    //字典转换为JSONString
    func getJSONStringFromDictionary() -> String {
        if (!JSONSerialization.isValidJSONObject(self)) {
            print("无法解析出JSONString")
            return ""
        }
        let data: Data! = try? JSONSerialization.data(withJSONObject: self, options: [])
        let JSONString = NSString(data:data as Data,encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
    
    ///获取字符串值
    func strValue(_ key:Key)->String{
        if let val = self[key] as? String {return val}
        if let val2 = self[key] as? Int {return "\(val2)"}
        if let val3 = self[key] as? Double {return "\(val3)"}
        if let val4 = self[key] as? CGFloat {return "\(val4)"}
        if let val5 = self[key] as? Float {return "\(val5)"}
        return ""
    }
    
    ///获取Int值
    func intValue(_ key:Key)->Int{
        if let va = self[key]{
            if let intVal = va as? Int{
                return intVal
            }
            return "\(va)".intValue()
        }
        return 0
    }
    
    ///获取Int值，replace若获取失败返回的值
    func intValue(_ key:Key,replace:Int)->Int{
        if let va = self[key]{
            return "\(va)".intValue()
        }
        return replace
    }
    
    ///获取字典
    func dictionary(_ key:Key)->[String:Any]{
        let dic = self[key] as? [String:Any] ?? [:]
        return dic
    }
    
    ///数组
    func array(_ key:Key)->[[String:Any]]{
        let array = self[key] as? [[String:Any]] ?? []
        return array
    }
    
    ///获取Double值
    func doubleValue(_ key:Key)->Double{
        if let va = self[key]{
            return "\(va)".doubleValue()
        }
        return 0
    }
}
